package controllers

import (
	"net/http"
	// "encoding/json"

	// "log"

	sessions "github.com/gorilla/sessions"
)

var (
	key = []byte("super-secret-key")
	store = sessions.NewCookieStore(key)
)


func LoginHandler(w http.ResponseWriter, r *http.Request) {
	if method := r.Method; method == "GET" {
		RenderTemplate(w, "login.html", nil)
		return
	}
	r.ParseForm()
	password := ""
	if len(r.Form["password"]) > 0 {
		password = r.Form["password"][0]
	}

	if password == "fpm123" {
		session, _ := store.Get(r, "cookie-name")
		// Set user as authenticated
		session.Values["authenticated"] = true
		session.Save(r, w)
		http.Redirect(w, r, "/", http.StatusFound)
	}else{
		http.Error(w, "Forbidden", http.StatusForbidden)
    return
	}

}

// ----------------------------------

// ----------------------------------
// The session handler.

func LogoutHandler(w http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, "cookie-name")

	// Revoke users authentication
	session.Values["authenticated"] = false
	session.Save(r, w)
	http.Redirect(w, r, "/", http.StatusFound)
}

func AuthOn(hFunc func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      // fmt.Println("AuthOn %v, token %v\n", r.URL.Path, r.Header)
      session, _ := store.Get(r, "cookie-name")

      // Check if user is authenticated
      if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
        http.Redirect(w, r, "/login", http.StatusFound)
        return
      }
      hFunc(w, r)
  })
}